/**
 * Created by linyi on 2019/3/15
 */
import React from 'react'
import PropTypes from 'prop-types'
import ReactDom from 'react-dom'
import { Tooltip } from 'antd'

function isOverflow(ele) {
  return ele.clientWidth < ele.scrollWidth
}

class LongText extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      overflow: false
    }
  }

  componentDidMount() {
    this.checkOverflow()
  }

  componentWillReceiveProps() {
    this.checkOverflow()
  }

  componentDidUpdate() {
    this.checkOverflow()
  }

  checkOverflow() {
    /* eslint-disable-next-line react/no-find-dom-node */
    const element = ReactDom.findDOMNode(this)
    const overflow = isOverflow(element)
    const { overflow: stateOverflow } = this.state
    if (overflow !== stateOverflow) {
      this.setState({ overflow: isOverflow(element) })
    }
  }

  render() {
    const { overflow } = this.state
    const { children, title } = this.props
    return !overflow ? (
      React.cloneElement(React.Children.only(children))
    ) : (
      <Tooltip title={title}>
        {React.cloneElement(React.Children.only(children))}
      </Tooltip>
    )
  }
}

LongText.propTypes = {
  title: PropTypes.node.isRequired
}

export default LongText
